package com.codeanalysissys.backend.ruby;

import com.codeanalysissys.backend.graphs.pdg.ControlDependenceGraph;
import com.codeanalysissys.backend.graphs.pdg.DataDependenceGraph;
import com.codeanalysissys.backend.graphs.pdg.PDGBuilder;
import com.codeanalysissys.backend.graphs.pdg.ProgramDependeceGraph;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class RubyPDGBuilder {
    public static ProgramDependeceGraph[] buildForAll(String[] rubyFilePaths) throws IOException {
        File[] rubyFiles = new File[rubyFilePaths.length];
        for (int i = 0; i < rubyFiles.length; ++i)
            rubyFiles[i] = new File(rubyFilePaths[i]);
        return buildForAll(rubyFiles);
    }

    public static ProgramDependeceGraph[] buildForAll(File[] rubyFiles) throws IOException {

        ControlDependenceGraph[] ctrlSubgraphs;
        ctrlSubgraphs = new ControlDependenceGraph[rubyFiles.length];
        for (int i = 0; i < rubyFiles.length; ++i)
            ctrlSubgraphs[i] = RubyCDGBuilder.build(rubyFiles[i]);
        //
        DataDependenceGraph[] dataSubgraphs;
        dataSubgraphs = RubyDDGBuilder.buildForAll(rubyFiles);
        //
        // Join the subgraphs into PDGs
        ProgramDependeceGraph[] pdgArray = new ProgramDependeceGraph[rubyFiles.length];
        for (int i = 0; i < rubyFiles.length; ++i) {
            pdgArray[i] = new ProgramDependeceGraph(rubyFiles[i].getName(),
                    ctrlSubgraphs[i], dataSubgraphs[i]);
        }

        return pdgArray;
    }

    public static ProgramDependeceGraph buildForOne(String fileName, InputStream inputStream) throws IOException {
        DataDependenceGraph dataSubgraphs;
        dataSubgraphs = RubyDDGBuilder.buildForOne(fileName, inputStream);
        //
        // Join the subgraphs into PDGs
        ProgramDependeceGraph pdgArray = new ProgramDependeceGraph(fileName, null, dataSubgraphs);
        return pdgArray;
    }

    public static ProgramDependeceGraph build(InputStream content) throws IOException {
        return new ProgramDependeceGraph(RubyCDGBuilder.build(content), RubyDDGBuilder.build(content));
    }
}
